package com.yidianyanglao.core.util;

import com.yidianyanglao.core.bean.RetBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Created by Administrator on 2016/11/2.
 */
public class  FileUploadOss {

    //图片后缀名
    public static final String PICSUFFIXS = ".jpg.jpeg.png.gif.JPG.JPEG.PNG.GIF";

    public static RetBean uploadPic(MultipartFile picFile) {
        String originalFilename = picFile.getOriginalFilename();
        String picSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(FileUploadOss.PICSUFFIXS.indexOf(picSuffix) == -1){
            throw  new CustomException(Code.ERROR,"后缀名不符合要求！");
        }

        String fileName = new Date().getTime() + picSuffix;

        try(InputStream input = picFile.getInputStream()){
            String key = OSSUtil.FILEPATH + fileName;
            OSSUtil.uploadFile(input, key, picFile.getSize());
            return new RetBean(Code.SUCCESS,"图片上传成功！",OSSUtil.OSS_URLPREFIX + "/" + key);
        }catch (final IOException e){
            Log.error("上传图片到OSS发生异常 ==> " + e.getMessage(), e);
            throw new CustomException(Code.ERROR,"上传图片到OSS发生异常！");
        }
    }

}
